package com.huluobo.a2204monthparkdemo.login

import android.content.Intent
import android.util.Log
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204monthparkdemo.MainActivity
import com.huluobo.a2204monthparkdemo.databinding.ActivityLoginBinding
import com.huluobo.base.bean.LoginBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

/**
 *  Created by LC on 2024/9/3.
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this) {
            val loginBean = Gson().fromJson(it, LoginBean::class.java)
            Log.i("TagA", "loginBean:${loginBean.uName}")
            SPUtils.getInstance().put(Const.PARAM_TOKEN, loginBean.token)
            SPUtils.getInstance().put(Const.PARAM_USERNAME, loginBean.uName)
            SPUtils.getInstance().put(Const.PARAM_PASSWORD, loginBean.uPwd)
            SPUtils.getInstance().put(Const.PARAM_USER_ID, loginBean.uId)
            viewModel.insertUserInfo(loginBean)
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }

    override fun initView() {
        if (SPUtils.getInstance().getString(Const.PARAM_USERNAME).isNotEmpty() && SPUtils.getInstance()
                .getString(Const.PARAM_PASSWORD).isNotEmpty()
        ) {
            val map = mutableMapOf<String, String>()
            map[Const.PARAM_USERNAME] = SPUtils.getInstance().getString(Const.PARAM_USERNAME)
            map[Const.PARAM_PASSWORD] = SPUtils.getInstance()
                .getString(Const.PARAM_PASSWORD)
            map[Const.PARAM_TIME] = (System.currentTimeMillis() / 1000).toString()

            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            viewModel.login(body)
        }

        binding.loginBtn.setOnClickListener {
            val username = binding.loginUsernameEt.text.toString()
            val password = binding.loginPasswordEt.text.toString()
            val time = (System.currentTimeMillis() / 1000).toString()

            val map = mutableMapOf<String, String>()
            map[Const.PARAM_USERNAME] = username
            map[Const.PARAM_PASSWORD] = password
            map[Const.PARAM_TIME] = time

            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            viewModel.login(body)

        }
    }
}